package com.bestcem.xm.user.util.business;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 根据占位符名称替换值
 *
 * @author panyun <yun.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/4 15:24
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class StringFormatUtil {

    private static final Pattern pattern = Pattern.compile("\\{[a-zA-Z0-9_]*}");

    /**
     * 格式化字符串
     *
     * @param sourStr 原字符串
     * @param param   参数变量
     * @return java.lang.String
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/26 22:36
     */
    public static String format(String sourStr, Map<String, Object> param) {
        String tagerStr = sourStr;
        if (Objects.isNull(param)) {
            return tagerStr;
        }
        try {
            Matcher matcher = pattern.matcher(tagerStr);
            while (matcher.find()) {
                String key = matcher.group();
                String keyclone = key.substring(1, key.length() - 1).trim();
                Object value = param.get(keyclone);
                if (value != null) {
                    tagerStr = tagerStr.replace(key, value.toString());
                }
            }
        } catch (Exception e) {
            return null;
        }
        return tagerStr;
    }

    /**
     * 读取html页面，并替换参数
     *
     * @param fileName 模板文件
     * @param map      参数
     * @return java.lang.String
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/7 11:23
     */
    public static String templateFormat(String fileName, Map<String, Object> map) {
        return format(readHtmlTemplateContent(fileName), map);
    }

    /**
     * 读取html文件模板内容
     *
     * @param fileName 文件信息
     * @return java.lang.String
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/26 22:43
     */
    public static String readHtmlTemplateContent(String fileName) {
        // 加载邮件html模板
        InputStream inputStream = StringFormatUtil.class.getResourceAsStream(fileName);
        assert inputStream != null;
        BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                builder.append(line);
            }
            inputStream.close();
            fileReader.close();
        } catch (Exception e) {
            log.error("读取文件失败，fileName:{}", fileName, e);
        }
        return builder.toString();
    }

}
